# -*- coding: utf-8 -*-
# @Time    : 2023/2/7 17:21
# @Author  : kali
import datetime

from database_init import db
from models import Tags, TagsHistory


def get_tags_data(req_data):
    """

    :param req_data:
    :return:
    """
    data = []
    count = 0
    try:
        page_size = int(req_data.get("page_size", 10))
        page_num = int(req_data.get("page_num", 1))
        query = req_data.get("query")
        if query:
            objs = Tags.query.filter(Tags.tag.like(query))
        else:
            objs = Tags.query.filter()
        count = objs.count()
        objs = objs.order_by(Tags.questions.desc()).paginate(page=page_num, per_page=page_size)

        for row in objs:
            data.append(row.to_dict())

        print(data)
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"get_tags_data error,msg:{str(e)}")
    return data, count


def add_or_update_tags_history(tag, questions, today_asked, week_asked):
    """

    :param tag:
    :param questions:
    :param today_asked:
    :param week_asked:
    :return:
    """
    try:
        today_str = datetime.datetime.utcnow().strftime("%Y-%m-%d")

        tags_history = TagsHistory.query.filter(TagsHistory.tag == tag, TagsHistory.date == today_str).first()
        if not tags_history:
            tags_history = TagsHistory()
            tags_history.tag = tag
            tags_history.questions = questions
            tags_history.today_asked = today_asked
            tags_history.week_asked = week_asked
            tags_history.date = today_str
            tags_history.save()
            return
        tags_history.questions = questions
        tags_history.today_asked = today_asked
        tags_history.week_asked = week_asked
        db.session.commit()
    except Exception as e:
        print(f"add_or_update_tags_history error,msg:{str(e)}")
